package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net"
	"os"
	. "qqtestprotocol"
	"strconv"
	"time"

	"gitee.com/viplianghl/golib/liangtcp"
	"github.com/jinzhu/configor"
)

var uid int64 = 0
var frds []int64
var g_tcpClient liangtcp.LiangTCPClient

func regist(p1 string, p2 string) {
	if uid != 0 {
		fmt.Println("Error, already login !")
		return
	}

	data := Protocol_regist{Cmd: "regist", Nick: p1, Pwd: p2}
	jsons, errs := json.Marshal(data)
	if errs != nil {
		return
	}

	g_tcpClient.SendMsg(jsons)
}
func login(p1 string, p2 string) {
	if uid != 0 {
		fmt.Println("Error, already login !")
		printPromote()
		return
	}

	l, err := strconv.ParseInt(p1, 10, 64)
	if err != nil {
		fmt.Println("Error, please input ID")
		printPromote()
		return
	}
	data := Protocol_login{Cmd: "login", Uid: l, Pwd: p2}
	jsons, errs := json.Marshal(data)
	if errs != nil {
		return
	}

	g_tcpClient.SendMsg(jsons)
}
func sendmsg(p1 string, p2 string) {
	if uid == 0 {
		fmt.Println("Error, please login !")
		return
	}

	l, err := strconv.ParseInt(p1, 10, 64)
	if err != nil {
		return
	}
	data := Protocol_msg{Cmd: "send", Uid: uid, Fid: l, Msg: p2}
	jsons, errs := json.Marshal(data)
	if errs != nil {
		return
	}

	g_tcpClient.SendMsg(jsons)
}
func add(p1 string, p2 string) {
	if uid == 0 {
		fmt.Println("Error, please login !")
		return
	}

	l, err := strconv.ParseInt(p1, 10, 64)
	if err != nil {
		return
	}
	data := Protocol_add_friend{Cmd: "add", Uid: uid, Fid: l}
	jsons, errs := json.Marshal(data)
	if errs != nil {
		return
	}

	g_tcpClient.SendMsg(jsons)
}
func del(p1 string, p2 string) {
	if uid == 0 {
		fmt.Println("Error, please login !")
		return
	}

	l, err := strconv.ParseInt(p1, 10, 64)
	if err != nil {
		return
	}
	data := Protocol_del_friend{Cmd: "del", Uid: uid, Fid: l}
	jsons, errs := json.Marshal(data)
	if errs != nil {
		return
	}

	g_tcpClient.SendMsg(jsons)
}
func friends() {
	if uid == 0 {
		fmt.Println("Error, please login !")
		return
	}
	// print friends
	fmt.Printf("friends: ")
	for i := 0; i < len(frds); i++ {
		fmt.Printf("%d ", frds[i])
	}
	fmt.Printf("\r\n")
	printPromote()
}

func save_uid_frds(buf []byte) error {
	// 	解析协议
	var cmd Protocol_success
	err := TransProtocol(buf, &cmd)
	if err != nil {
		log.Println("QQtest transProtocol Protocol_success err: ", err)
		return err
	}

	uid = cmd.Uid
	frds = cmd.Friends
	printPromote()
	return nil
}

func onDisconn(conn net.Conn) error {
	return nil
}

func onMsg(conn net.Conn, buf []byte) error {
	log.Println("reve data (from ", conn.RemoteAddr().String(), "): ", string(buf))
	printPromote()

	var cmd Protocol_cmd
	err := TransProtocol(buf, &cmd)
	if err != nil {
		log.Println("QQtest transProtocol cmd err: ", err)
		return err
	}

	switch cmd.Cmd {
	case "success":
		// save uid, frds
		save_uid_frds(buf)
	case "send":
		// printf send msg
		var data Protocol_msg
		err1 := TransProtocol(buf, &data)
		if err1 != nil {
			log.Println("QQtest transProtocol msg err: ", err1)
			return err1
		}
		log.Printf("msg（from %d to %d）: %s\r\n [%d]$ ", data.Uid, data.Fid, data.Msg, uid)
		printPromote()
	}

	return nil
}

func printPromote() {
	if uid == 0 {
		fmt.Printf("Go ahead with cmd reg/login/exit:\r\n [0]$ ")
	} else {
		fmt.Printf("Go ahead with cmd send/friends/add/del/exit:\r\n [%d]$ ", uid)
	}
}

var Config = struct {
	Connstr string `required:"true"`
}{}

func main() {
	g_tcpClient.OnDisconn = onDisconn
	g_tcpClient.OnMsg = onMsg

	configor.Load(&Config, "./config.yml")
	var connStr string = Config.Connstr
	if len(os.Args) > 1 {
		connStr = os.Args[1]
	}
	err := g_tcpClient.Connect(connStr)
	if err != nil {
		fmt.Println("Error, tcp connect failed! ", connStr, err)
		return
	}

	time.Sleep(time.Duration(2) * time.Second)
	for {
		printPromote()

		var cmd, p1, p2 string
		fmt.Scanln(&cmd, &p1, &p2)
		switch cmd {
		case "exit":
			return
		case "reg":
			regist(p1, p2)
		case "login":
			login(p1, p2)
		case "send":
			sendmsg(p1, p2)
		case "friends":
			friends()
		case "add":
			add(p1, p2)
		case "del":
			del(p1, p2)
		default:
			fmt.Println("Error, unknown cmd !")
		}
	}
}
